package Cantella::DJabberd::Web::UI::ViewPort::Field::Collection::Linked;

use Reaction::Class;
use aliased 'Reaction::UI::ViewPort::Action::Link';

extends 'Reaction::UI::ViewPort::Field::Collection';

has members => ( is => 'rw', isa => 'ArrayRef', lazy_build => 1 );
has prototype => ( is => 'rw', isa => 'CodeRef');
has controller => ( is => 'ro', isa => 'Str' );

has action =>
  (
   is => 'ro',
   isa => 'Str',
   required => 1,
   default => sub{ 'view' },
  );

sub BUILD {
  my $self = shift;
  if( !$self->has_prototype && $self->has_controller ){
    my $controller = $self->controller;
    my $action = $self->action;
    my $proto =  sub {
      [ "${controller}", "${action}", [ $_[0]->__id ] ],
    };
    $self->prototype($proto);
  }
}

sub _build_members {
  my $self = shift;
  my @members;
  if( $self->has_prototype ){
    my $prototype = $self->prototype;
    my $meth = $self->value_map_method;
    for my $member ( $self->value->members ){
      my $link = Link->new
        (
         ctx => $self->ctx,
         location => join('-', $self->location, $member->__id ),
         label => $member->$meth,
         target => $member,
         action => $prototype
        );
      push(@members, $link);
    }
  }
  return \@members;
}

__PACKAGE__->meta->make_immutable;

1;
